package com.test.ssm.controller;

import com.test.ssm.pojo.HotelOrder;
import com.test.ssm.service.HotelService;
import com.test.ssm.service.OrderService;
import com.test.ssm.wechat.PayUtil;
import com.test.ssm.wechat.WXPayUtil;
import com.test.ssm.wechat.ZxingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 徒有琴
 */
@Controller
public class PayController {
    @RequestMapping("wxorder.html")
    public void wxorder(String orderNum, Integer price, HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", PayUtil.APP_ID);
        params.put("mch_id", PayUtil.MCH_ID);
        params.put("nonce_str", System.currentTimeMillis() + "");
        params.put("body", "卢本伟的挂");
        params.put("out_trade_no", orderNum);
        params.put("total_fee", price.toString());
        params.put("spbill_create_ip", request.getRemoteAddr());
        params.put("notify_url", "http://2361k301i0.iok.la:10923/wcallback.html");
        params.put("trade_type", "NATIVE");
        try {
            String xml = WXPayUtil.generateSignedXml(params, PayUtil.API_KEY);
            // System.out.println(xml);
            String res = PayUtil.doPost("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
            // System.out.println(res);
            Map<String, String> result = WXPayUtil.xmlToMap(res);
            System.out.println(result.get("code_url"));
            BufferedImage img = ZxingUtil.createImage(result.get("code_url"), 300, 300);
            ImageIO.write(img, "JPEG", response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String WX_SUCCESS = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    private String WX_ERROR = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>";
    //<xml><appid><![CDATA[wx632c8f211f8122c6]]></appid><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[N]]></is_subscribe><mch_id><![CDATA[1497984412]]></mch_id><nonce_str><![CDATA[1574823036003]]></nonce_str><openid><![CDATA[oUuptwolHj8j7wlH1V3TVZPDdkmg]]></openid><out_trade_no><![CDATA[201911271050]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[DF426C8E9EA7BA3E0A2C34047F72B781]]></sign><time_end><![CDATA[20191127105057]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[NATIVE]]></trade_type><transaction_id><![CDATA[4200000460201911274110734331]]></transaction_id></xml>
    @Autowired
    private OrderService orderService;

    @RequestMapping("wcallback.html")
    public void callback(HttpServletRequest request, HttpServletResponse response) {
        InputStream inputStream = null;
        StringBuilder builder = new StringBuilder();
        try {
            inputStream = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            inputStream.close();
            String xml = builder.toString();
            System.out.println(xml);
            boolean check = WXPayUtil.isSignatureValid(xml, PayUtil.API_KEY);
            if (check) {
                //先判断订单状态，如果订单已经更新过了，直接响应成功，否则更新订单状态
                Map<String, String> result = WXPayUtil.xmlToMap(xml);
                String orderNum = result.get("out_trade_no");
                HotelOrder order = orderService.getOrderByNum(orderNum);
                if (order != null && order.getStatus() == 0) {//未支付
                    if ("SUCCESS".equals(result.get("result_code"))) {
                        order.setStatus(1);
                        //验证金额对不对

                    } else {
                        order.setStatus(-1);
                    }
                    // order.setCallback("xml中有用的其它信息");
                    order.setTradeNum(result.get("transaction_id"));
                    order.setPayTime(new Date());
                    orderService.updateOrder(order);
                }
                ChactController.send(orderNum, "支付成功");
                response.getWriter().write(WX_SUCCESS);
            } else {
                System.out.println("签名失败");
                response.getWriter().write(WX_ERROR);
            }

        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.getWriter().write(WX_ERROR);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    @RequestMapping("gochat.html")
    public String chat() {
        return "chat";
    }
}
